from datetime import datetime
from sqlalchemy import ForeignKey, UniqueConstraint, Column
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql.sqltypes import String, Integer, Text, DateTime
from app.core.base_model import BaseModel


class SQLProcessor(BaseModel):
    __tablename__ = 't_proc_sql'
    sql_text = Column(Text, nullable=False)
    sql_brief = Column(String(100), nullable=True)
    sql_type = Column(String(8), nullable=False)
    proc_state = Column(String(8), nullable=False, default='0')
    affect_rows = Column(Integer)
    proc_result = Column(Text)

    def __init__(self, sql_text, sql_type, proc_state):
        sql_text2 = sql_text.strip()  # 去除首尾空格
        self.sql_text = sql_text2
        self.sql_type = sql_type
        self.proc_state = proc_state  # 处理状态，默认0-初始状态
        self.gen_sql_brief()

    def gen_sql_brief(self):
        if self.sql_brief is None:
            sql_brief = self.sql_text.replace('\n', ' ').replace('\r', ' ')  # 去除换行符
            sql_brief = sql_brief.replace('  ', ' ')  # 去除重复的空格
            self.sql_brief = sql_brief[0:80]

    def __repr__(self):
        return '[%r]%s' % (self.id, self.sql_brief)
